package com.mysiteforme.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.mysiteforme.admin.entity.*;
import com.mysiteforme.admin.service.ElectricityMessagePushDescService;
import com.mysiteforme.admin.service.ElectricityPushFreemakerService;
import com.mysiteforme.admin.service.ElectricityUserService;
import com.mysiteforme.admin.util.*;
import org.apache.el.lang.ELArithmetic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mysiteforme.admin.service.ElectricityMessagePushService;
import com.baomidou.mybatisplus.plugins.Page;
import com.mysiteforme.admin.annotation.SysLog;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.ServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * 消息推送表  前端控制器
 * </p>
 *
 * @author wangl
 * @since 2019-10-22
 */
@Controller
@RequestMapping("/admin/electricityMessagePush")
public class ElectricityMessagePushController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ElectricityMessagePushController.class);

    @Autowired
    private ElectricityMessagePushService electricityMessagePushService;
    @Autowired
    private ElectricityMessagePushDescService electricityMessagePushDescService;
    @Autowired
    private ElectricityPushFreemakerService electricityPushFreemakerService;
    @Autowired
    private ElectricityUserService electricityUserService;
    @Autowired
    private SendMessagePush sendMessagePush;

    @GetMapping("list")
    @SysLog("跳转消息推送表列表")
    public String list() {
        return "/admin/electricityMessagePush/list";
    }

    @PostMapping("list")
    @ResponseBody
    @SysLog("请求消息推送表列表数据")
    public LayerData<ElectricityMessagePush> list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                                  @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                                                  ServletRequest request) {
        Map map = WebUtils.getParametersStartingWith(request, "s_");
        LayerData<ElectricityMessagePush> layerData = new LayerData<>();
        EntityWrapper<ElectricityMessagePush> wrapper = new EntityWrapper<>();
        wrapper.eq("del_flag", false);
        if (!map.isEmpty()) {
            String messageType = (String) map.get("messageType");
            if (StringUtils.isNotBlank(messageType)) {
                wrapper.eq("message_type", messageType);
            } else {
                map.remove("messageType");
            }

            String isWechat = (String) map.get("isWechat");
            if (StringUtils.isNotBlank(isWechat)) {
                wrapper.eq("is_wechat", isWechat);
            } else {
                map.remove("isWechat");
            }

            String pushStatus = (String) map.get("pushStatus");
            if (StringUtils.isNotBlank(pushStatus)) {
                wrapper.eq("push_status", pushStatus);
            } else {
                map.remove("pushStatus");
            }

            String title = (String) map.get("title");
            if (StringUtils.isNotBlank(title)) {
                wrapper.like("title", title);
            } else {
                map.remove("title");
            }

        }
        Page<ElectricityMessagePush> pageData = electricityMessagePushService.selectPage(new Page<>(page, limit), wrapper);
        for (ElectricityMessagePush electricityMessagePush : pageData.getRecords()) {
            electricityMessagePush.setStringId(String.valueOf(electricityMessagePush.getId()));
            EntityWrapper<ElectricityPushFreemaker> pushFreemakerEntityWrapper = new EntityWrapper<>();
            pushFreemakerEntityWrapper.eq("freemaker_Id", electricityMessagePush.getFreemakerId());
            ElectricityPushFreemaker pushFreemaker = electricityPushFreemakerService.selectOne(pushFreemakerEntityWrapper);
            if (pushFreemaker != null) {
                electricityMessagePush.setFreemakerName(pushFreemaker.getFreemakerName());
            }
        }
        layerData.setData(pageData.getRecords());
        layerData.setCount(pageData.getTotal());
        return layerData;
    }

    @GetMapping("add")
    @SysLog("跳转新增消息推送表页面")
    public String add() {
        return "/admin/electricityMessagePush/add";
    }

    @PostMapping("add")
    @SysLog("保存新增消息推送表数据")
    @ResponseBody
    public RestResponse add(String data, String type) {
        JSONObject jsonObject = JSONObject.parseObject(data);
        String isWechat = jsonObject.getString("isWechat");
        String title = jsonObject.getString("title");
        String content = jsonObject.getString("content");
        String freemakerId = jsonObject.getString("freemakerId");
        if (type.equals("1") && isWechat.equals("1")) {
            ElectricityPushFreemaker electricityPushFreemaker = electricityPushFreemakerService.selectById(freemakerId);
            if (electricityPushFreemaker.getFreemakerId() != null) {
                messageSend(data, type, electricityPushFreemaker.getFreemakerId());
            }
        } else {
            ElectricityMessagePush electricityMessagePush = new ElectricityMessagePush();
            electricityMessagePush.setMessageType("1");
            electricityMessagePush.setIsWechat(isWechat);
            electricityMessagePush.setPushStatus(type);
            if (type.equals("1")) {//1 微信推送 2系统推送
                electricityMessagePush.setPushDate(new Date());
            }

            electricityMessagePush.setTitle(title);
            electricityMessagePush.setContent(content);
            if (isWechat.equals("1")) {//1 微信推送 2系统推送
                electricityMessagePush.setType("1");//type  0系统推送  1.非系统推送
            } else if (isWechat.equals("2")) {
                electricityMessagePush.setType("0");
            }
            electricityMessagePushService.insert(electricityMessagePush);

        }
        return RestResponse.success(true);
    }

    /****
     * 立即推送
     * @return
     * @throws
     */
    public RestResponse messageSend(String data, String type, String freemakerId) {
        JSONObject jsonObject = JSONObject.parseObject(data);
        String isWechat = jsonObject.getString("isWechat");
        String freemaker_Id = jsonObject.getString("freemakerId");
        String title = jsonObject.getString("title");
        String content = jsonObject.getString("content");
        JSONObject wxList = JSONObject.parseObject(jsonObject.getString("wxList"));
        if (wxList == null) {
            return RestResponse.failure("组装微信信息失败");
        }
        RestResponse rs = send(wxList, freemakerId);
         /* Set<String> set1 = rs.keySet();
        for (String key : set1) {
            String wxCode = key;
            if (!wxCode.equals("success")) {
                return rs;
            }
        }*/

        ElectricityMessagePush electricityMessagePush = new ElectricityMessagePush();
        electricityMessagePush.setMessageType("1");
        electricityMessagePush.setIsWechat(isWechat);
        electricityMessagePush.setPushStatus(type);
        electricityMessagePush.setPushDate(new Date());
        electricityMessagePush.setTitle(title);
        electricityMessagePush.setContent(content);
        if (isWechat.equals("1")) {//1 微信推送 2系统推送
            electricityMessagePush.setType("1");//type  0系统推送  1.非系统推送
        } else if (isWechat.equals("2")) {
            electricityMessagePush.setType("0");
        }
        if (freemaker_Id != null && !freemaker_Id.equals("")) {
            EntityWrapper<ElectricityPushFreemaker> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq("id", freemaker_Id);
            ElectricityPushFreemaker electricityPushFreemaker = electricityPushFreemakerService.selectOne(entityWrapper);
            electricityMessagePush.setFreemakerId(electricityPushFreemaker.getFreemakerId());
        }
        electricityMessagePushService.insert(electricityMessagePush);

        boolean i;
        if (wxList.size() != 0) {
            String wxDesc = jsonObject.getString("wxDesc");
            ElectricityMessagePushDesc electricityMessagePushDesc = new ElectricityMessagePushDesc();

            if (wxList != null && wxList.size() > 0) {
                Set<String> set = wxList.keySet();
                for (String key : set) {
                    String wxCode = key;
                    wxDesc = wxList.getString(wxCode);
                    System.out.println("desc====" + wxDesc);
                    if (!wxCode.equals("wxCode")) {
                        electricityMessagePushDesc.setPushId(electricityMessagePush.getId().toString());
                        electricityMessagePushDesc.setWxCode(wxCode);
                        electricityMessagePushDesc.setWxDesc(wxDesc);
                        i = electricityMessagePushDescService.insert(electricityMessagePushDesc);
                        if (!i) {
                            return RestResponse.failure("失败");
                        }
                    }
                }
            } else {
                electricityMessagePushDesc.setPushId(electricityMessagePush.getId().toString());
                electricityMessagePushDesc.setWxDesc(wxDesc);
                i = electricityMessagePushDescService.insert(electricityMessagePushDesc);
                if (!i) {
                    return RestResponse.failure("失败");
                }
            }
        }

        EntityWrapper<ElectricityMessagePushDesc> descEntityWrapper = new EntityWrapper<>();
        descEntityWrapper.eq("push_id", electricityMessagePush.getId());
        List<ElectricityMessagePushDesc> messagePushDescList = electricityMessagePushDescService.selectList(descEntityWrapper);

        electricityMessagePush.setMessagePushDescList(messagePushDescList);
        electricityMessagePushService.updateById(electricityMessagePush);

        return rs;
    }

    /**
     * 发送
     **/
    public RestResponse send(JSONObject wxList, String freemakerId) {
        EntityWrapper<ElectricityUser> queryWrapper = new EntityWrapper<>();
        queryWrapper.eq("del_flag", "0");
        List<ElectricityUser> userList = electricityUserService.selectList(queryWrapper);
        if (userList == null || userList.size() < 1) {
            return RestResponse.failure("未查询到用户,微信消息推送失败");
        }
        int j = 0;
        for (int i = 0; i < userList.size(); i++) {
            String openid = userList.get(i).getOpenid();
            if (StringUtils.isNotEmpty(openid)) {
                JSONObject json = new JSONObject();
                if (wxList != null && wxList.size() > 0) {
                    Set<String> set = wxList.keySet();
                    for (String key : set) {
                        String wxCode = key;
                        String wxDesc = wxList.getString(wxCode);
                        System.out.println("desc====" + wxDesc);
                        if (wxCode.equals("first描述")) {
                            SendMessagesTemplete sendMessagesTemplete = new SendMessagesTemplete(
                                    wxDesc, Constants.MEESSAGE_PUSH_COLOUR);
                            json.put("first", sendMessagesTemplete);
                        }
                        if (wxCode.equals("管理员")) {
                            //管理员
                            SendMessagesTemplete sendMessagesTemplete1 = new SendMessagesTemplete(wxDesc, Constants.MEESSAGE_PUSH_COLOUR);
                            json.put("keyword1", sendMessagesTemplete1);
                        }
                        if (wxCode.equals("到期日期")) {
                            //到期日期
                            SendMessagesTemplete sendMessagesTemplete2 = new SendMessagesTemplete(wxDesc, "#f84a0a");
                            json.put("keyword2", sendMessagesTemplete2);
                        }
                        if (wxCode.equals("剩余天数")) {
                            //剩余天数
                            SendMessagesTemplete sendMessagesTemplete3 = new SendMessagesTemplete(wxDesc + "天", "#f84a0a");
                            json.put("keyword3", sendMessagesTemplete3);
                        }
                        if (wxCode.equals("备注")) {
                            SendMessagesTemplete templete3 = new SendMessagesTemplete(wxDesc, Constants.MEESSAGE_PUSH_COLOUR);
                            json.put("remark", templete3);
                        }
                    }

                    try {
                        boolean b = true;
                        do {
                            Response<?> rs = sendMessagePush.sendMessagePush("oSqaLv3tK88kZRD25ubNgNrNZXQM", freemakerId,
                                    null, json, Constants.MEESSAGE_PUSH_COLOUR);
                            //如果返回状态码为40001则重新发送
                            b = electricityMessagePushService.getBoolean(b, rs, "通知用户", i);
                            j++;
                        } while (b);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return RestResponse.failure("发起微信消息推送失败");
                    }
                }

            }
            continue;
        }
        String msg = "关注本公众号并推送成功的人数:" + j;
        return RestResponse.success(msg);
    }

    @GetMapping("edit")
    @SysLog("跳转编辑消息推送表页面")
    public String edit(Long id, Model model) {
        ElectricityMessagePush electricityMessagePush = electricityMessagePushService.selectById(id);
        model.addAttribute("electricityMessagePush", electricityMessagePush);
        if (electricityMessagePush.getFreemakerId() != null) {
            EntityWrapper<ElectricityPushFreemaker> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq("freemaker_id", electricityMessagePush.getFreemakerId());
            ElectricityPushFreemaker electricityPushFreemaker = electricityPushFreemakerService.selectOne(entityWrapper);
            model.addAttribute("electricityPushFreemaker", electricityPushFreemaker);
        }
        return "/admin/electricityMessagePush/edit";
    }

    @PostMapping("edit")
    @ResponseBody
    @SysLog("保存编辑消息推送表数据")
    public RestResponse edit(String data, String type) {
        JSONObject jsonObject = JSONObject.parseObject(data);
        String id = jsonObject.getString("id");
        String messageType = jsonObject.getString("messageType");
        String isWechat = jsonObject.getString("isWechat");
        String freemakerId = jsonObject.getString("freemakerId");
        String title = jsonObject.getString("title");
        String content = jsonObject.getString("content");
        JSONObject wxList = JSONObject.parseObject(jsonObject.getString("wxList"));
        if (type.equals("1") && isWechat.equals("1")) {
            ElectricityPushFreemaker electricityPushFreemaker = electricityPushFreemakerService.selectById(freemakerId);
            RestResponse rs = send(wxList, electricityPushFreemaker.getFreemakerId());
            ElectricityMessagePush electricityMessagePush = electricityMessagePushService.selectById(id);
            electricityMessagePush.setMessageType(messageType);
            electricityMessagePush.setIsWechat(isWechat);
            electricityMessagePush.setPushStatus(type);
            electricityMessagePush.setPushDate(new Date());
            electricityMessagePush.setTitle(title);
            electricityMessagePush.setContent(content);
            if (isWechat.equals("1")) {//1 微信推送 2系统推送
                electricityMessagePush.setType("1");//type  0系统推送  1.非系统推送
            } else if (isWechat.equals("2")) {
                electricityMessagePush.setType("0");
            }

            if (freemakerId != null && !freemakerId.equals("")) {
                EntityWrapper<ElectricityPushFreemaker> entityWrapper = new EntityWrapper<>();
                entityWrapper.eq("id", freemakerId);
                electricityPushFreemaker = electricityPushFreemakerService.selectOne(entityWrapper);
                electricityMessagePush.setFreemakerId(electricityPushFreemaker.getFreemakerId());
            }

            String wxDesc = jsonObject.getString("wxList");
            EntityWrapper<ElectricityMessagePushDesc> descEntityWrapper = new EntityWrapper<>();
            descEntityWrapper.eq("push_id", electricityMessagePush.getId());
            List<ElectricityMessagePushDesc> messagePushDescList = electricityMessagePushDescService.selectList(descEntityWrapper);

            electricityMessagePush.setMessagePushDescList(messagePushDescList);
            electricityMessagePushService.updateById(electricityMessagePush);


            if (wxList != null && wxList.size() > 0) {

                Set<String> set = wxList.keySet();
                for (String key : set) {
                    String wxCode = key;
                    wxDesc = wxList.getString(wxCode);
                    System.out.println("desc====" + wxDesc);
                    if (!wxCode.equals("wxCode") && !wxCode.equals("")) {
                        for (ElectricityMessagePushDesc s : messagePushDescList) {
                            if (s.getWxCode().equals(wxCode)) {
                                s.setPushId(electricityMessagePush.getId().toString());
                                s.setWxCode(wxCode);
                                s.setWxDesc(wxDesc);
                                electricityMessagePushDescService.updateById(s);
                            }

                        }
                    } else if (!wxCode.equals("wxCode") && wxCode.equals("")) {
                        for (ElectricityMessagePushDesc s : messagePushDescList) {
                            s.setPushId(electricityMessagePush.getId().toString());
                            s.setWxCode(wxCode);
                            s.setWxDesc(wxDesc);
                            electricityMessagePushDescService.updateById(s);
                        }
                    }
                }
            }

        }else{
            ElectricityMessagePush electricityMessagePush = electricityMessagePushService.selectById(id);
            electricityMessagePush.setMessageType(messageType);
            electricityMessagePush.setIsWechat(isWechat);
            electricityMessagePush.setPushStatus(type);
            if (type.equals("1")) {//1 微信推送 2系统推送
                electricityMessagePush.setPushDate(new Date());
            }
            electricityMessagePush.setTitle(title);
            electricityMessagePush.setContent(content);
            if (isWechat.equals("1")) {//1 微信推送 2系统推送
                electricityMessagePush.setType("1");//type  0系统推送  1.非系统推送
            } else if (isWechat.equals("2")) {
                electricityMessagePush.setType("0");
            }
            electricityMessagePushService.updateById(electricityMessagePush);
        }


        return RestResponse.success();
    }

    @GetMapping("view")
    @SysLog("跳转编辑消息推送表页面")
    public String view(Long id, Model model) {
        ElectricityMessagePush electricityMessagePush = electricityMessagePushService.selectById(id);
        model.addAttribute("electricityMessagePush", electricityMessagePush);
        if (electricityMessagePush.getFreemakerId() != null) {
            EntityWrapper<ElectricityPushFreemaker> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq("freemaker_id", electricityMessagePush.getFreemakerId());
            ElectricityPushFreemaker electricityPushFreemaker = electricityPushFreemakerService.selectOne(entityWrapper);
            model.addAttribute("electricityPushFreemaker", electricityPushFreemaker);
        }
        return "/admin/electricityMessagePush/view";
    }

    @PostMapping("queryMessageDesc")
    @ResponseBody
    @SysLog("获取模板描述信息")
    public Object queryMessageDesc(@RequestParam(value = "id", required = false) String id) {

        if (StringUtils.isBlank(id)) {
            return RestResponse.failure("id不能为空");
        }
        EntityWrapper<ElectricityMessagePushDesc> descWrapper = new EntityWrapper<>();
        descWrapper.eq("push_id", id);
        List<ElectricityMessagePushDesc> descList = electricityMessagePushDescService.selectList(descWrapper);
        return descList;
    }

    @PostMapping("delete")
    @ResponseBody
    @SysLog("删除消息推送表数据")
    public RestResponse delete(@RequestParam(value = "id", required = false) Long id) {
        if (null == id || 0 == id) {
            return RestResponse.failure("ID不能为空");
        }
        ElectricityMessagePush electricityMessagePush = electricityMessagePushService.selectById(id);
        electricityMessagePush.setDelFlag(true);
        electricityMessagePushService.updateById(electricityMessagePush);

        EntityWrapper<ElectricityMessagePushDesc> descEntityWrapper = new EntityWrapper<>();
        descEntityWrapper.eq("push_id", electricityMessagePush.getId());
        List<ElectricityMessagePushDesc> descList = electricityMessagePushDescService.selectList(descEntityWrapper);
        for (ElectricityMessagePushDesc desc : descList) {
            desc.setDelFlag(true);
            electricityMessagePushDescService.updateById(desc);
        }
        return RestResponse.success();
    }

}